map() 創建一個新陣列並儲存進行操作後的結果 原始陣列還會存在
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // 輸出新陣列 [1, 4, 9, 16, 25]
slice() 提取begin~end的元素(不包括end)
const fruits = ["蘋果","香蕉","柳丁","草莓"];
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // 輸出 ["香蕉","柳丁"]
filter() 將滿足指定條件的元素存到新陣列
let ary = [1,2,3];
let newAry = ary.filter(function(item, index, array){
return item == 1;
});
console.log(newAry); // [1]
newAry = ary.filter(function(item, index, array){
return item <= 2;
});
console.log(newAry); // [1, 2]
newAry = ary.filter(function(item, index, array){
return item < 4;
});
console.log(newAry); // []
split()根據所設定的字符做分割
let message = 'Go lucky Guy';
let strAry = message.split(''); // 代入空字串當分隔符
console.log(strAry); // ['G', 'o', ' ', 'l', 'u', 'c', 'k', 'y', ' ', 'G', 'u', 'y']
strAry = message.split('', 5); // 代入空字串當分隔符
console.log(strAry); // ['G', 'o', ' ', 'l', 'u']
strAry = message.split(' '); // 代入空白當分隔符
console.log(strAry); // ['Go', 'lucky', 'Guy']
strAry = message.split(' ', 5);
console.log(strAry); // ['Go', 'lucky', 'Guy']
strAry = message.split(' ', 1);
console.log(strAry); // ['Go']
strAry = message.split('G');
console.log(strAry); // ['', 'o lucky ', 'uy']
本篇部分程式碼來自https://hackmd.io/@Calon/By3akyNOt